<template>
  <div :class="{'order-info': isHasBackground}">
    <Title :tip="tip" title="订单信息" style="margin-bottom: 32px;" >
      <el-tooltip v-if="tip && tip!==''" placement="top" effect="dark">
      <div slot="content" style="max-width: 200px;">{{ tip }}</div>
      <tipIcon is-diy style="color:#406EFF;font-size:14px;margin-left: 5px;cursor: pointer;"/>
      </el-tooltip>
    </Title>
    <div class="order-form">
      <el-form
        ref="formRef"
        :model="paramsObj"
        :rules="rules"
        label-position="left"
        class="edit-order"
        label-width="95px">
        <div class="left">
          <el-form-item label="销售" prop="marketId">
            <selectWithoutHttp
              :disabled="disabledTaxAmount || isDisabledWithoutFile "
              v-model="clientParams.marketId"
              :default-list="defaultMarketOption"
              :remote-method="masketList"
              :list-data="marketOption"
              filterable
              remote
              placeholder="请输入销售名称可快速查找"
              @changeInfo="marketChange"
            />
          </el-form-item>
          <el-form-item label="下单日期" prop="orderTime">
            <el-date-picker
              v-model="paramsObj.orderTime"
              :clearable="false"
              :editable="false"
              :disabled="isDisabledWithoutFile || editLimt"
              type="date"
              value-format="timestamp"
              size="small"
              class="order-time"
              format="yyyy/MM/dd"/>
          </el-form-item>
          <el-form-item label="含税金额" prop="taxAmount">
            <el-input
              v-model="paramsObj.taxAmount"
              :disabled="disabledTaxAmount || isDisabledWithoutFile || editLimt || taxAmountDisabled"
              oninput="if(value>9999999999999999.00)value=1000000000000000"
              name="taxAmount"
              type="number"
              size="small"
              @change="numberInputChange('taxAmount')"
              @mousewheel.native.prevent
              @blur="mathPlanPrice"
            />
          </el-form-item>
          <el-form-item label="渠道价" prop="channelPrice">
            <el-input v-model="paramsObj.channelPrice" name="channelPrice" type="text" size="small" disabled />
          </el-form-item>
          <el-form-item label="折扣" prop="discountPrice">
            <el-input v-model="paramsObj.discountPrice" name="discountPrice" type="text" size="small" disabled />
          </el-form-item>
          <el-form-item label="品牌名称" prop="theme" class="theme">
            <el-input :disabled="isDisabledWithoutFile || editLimt" v-model.trim="paramsObj.theme" name="theme" type="text" size="small" maxlength="50" />
          </el-form-item>
          <el-form-item label="订单分类" prop="terminalType" class="terminalType">
            <selectWithUserLoad
              ref="selectProjectDirector"
              v-model="paramsObj.orderKind"
              :is-no-loading="true"
              :multiple="true"
              :default-list="defaultObjectUser || []"
              :loadmore-method="getOrderKindList"
              :multiple-limit="5"
              value-type="object"
              key-name="id"
              label-name="orderKindName"
              clearable
              filterable/>
          </el-form-item>
          <el-form-item label="收入类型" prop="incomeType">
            <selectWithoutHttp
              v-model="paramsObj.incomeType"
              :disabled="isDisabledWithoutFile"
              :list-data="incomeOption"
              key-name="id"
              label-name="name"
            />
          </el-form-item>

          <el-form-item label="备注" prop="remark" style="margin-bottom: 0">
            <el-input
              :disabled="isDisabledWithoutFile"
              :autosize="{minRows: 2, maxRows: 6}"
              v-model.trim="paramsObj.remark"
              resize="none"
              name="remark"
              type="textarea"
              maxlength="500"
              style="width: 240px;height: 64px" />
          </el-form-item>
        </div>
        <div class="right">
          <el-form-item label="策划执行人" prop="mastermindId">
            <selectWithoutHttp
              :disabled="disabledTaxAmount || isDisabledWithoutFile "
              v-model="clientParams.mastermindId"
              :remote-method="(val) => {masketList(val, 1)}"
              :default-list="defaultMastermindOption"
              :list-data="marketmindOption"
              clearable
              filterable
              remote
              placeholder="请输入该订单负责的博主或策划人"
            />
          </el-form-item>

          <el-form-item v-if="isShowInput('orderType')" label="订单类型" prop="orderType">
            <selectWithoutHttp
              v-model="paramsObj.orderType"
              :disabled="isDisabledWithoutFile || isEdit"
              :list-data="orderTypeList"
              key-name="value"
              label-name="label"
              @change="orderTypeChange"
            />
          </el-form-item>
          <el-form-item v-if="isShowInput('projectType')" label="项目类型" prop="projectType">
            <el-select
              v-model="paramsObj.projectType"
              popper-class="global-select-down"
              name="orderForm"
              size="small"
            >
              <el-option
                v-for="item in projectTypesOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="策划价" prop="planPrice">
            <el-input
              v-model="paramsObj.planPrice"
              :disabled="disabledTaxAmount || isDisabledWithoutFile "
              oninput="if(value>9999999999999999.00)value=1000000000000000"
              name="planPrice"
              type="number"
              size="small"
              @change="numberInputChange('planPrice')"
              @mousewheel.native.prevent
              @blur="mathPlanPrice"
            />
          </el-form-item>
          <el-form-item label="刊例价" prop="articlesPrice">
            <el-input
              v-model="paramsObj.articlesPrice"
              :disabled="disabledTaxAmount || isDisabledWithoutFile || editLimt"
              oninput="if(value>9999999999999999.00)value=1000000000000000"
              name="articlesPrice"
              type="number"
              size="small"
              @change="numberInputChange('articlesPrice')"
              @mousewheel.native.prevent
              @blur="mathDiscount"
            />
          </el-form-item>
          <el-form-item label="结算基数" prop="priceBase">
            <el-input
              v-model="paramsObj.priceBase"
              oninput="if(value>9999999999999999.00)value=9999999999999999"
              name="priceBase"
              type="number"
              size="small"
              @change="numberInputChange('priceBase')"
              @mousewheel.native.prevent
            />
          </el-form-item>
          <el-form-item label="终端品牌" prop="terminalType" class="terminalType">
            <el-input :disabled="isDisabledWithoutFile" v-model.trim="paramsObj.terminalType" name="terminalType" type="text" size="small" maxlength="50" />
          </el-form-item>
          <el-form-item label="订单来源" prop="orderSource">
            <selectWithoutHttp
              v-model="paramsObj.orderSource"
              :list-data="orderSourceOptions"
              key-name="id"
              label-name="name"
            />
          </el-form-item>
          <el-form-item label="IP形象">
            <div>
              <selectWithUserLoad
                ref="selectUser"
                v-model="paramsObj.ip"
                :select-data-list="paramsObj.ip || []"
                :loadmore-method="getipFigure()"
                multiple
                style="width:240px;"
                placeholder="请选择IP形象"
                value-type="object"
                key-name="ipId"
                label-name="name"
                extend-class="ip-image"
                filterable
                collapse-tags
                clearable
                @change="ipFigureChange" />
            </div>
          </el-form-item>
          <el-form-item label="文案内容" prop="content" class="content">
            <el-input :disabled="isDisabledWithoutFile || editLimt" :autosize="{minRows: 2, maxRows: 6}" v-model.trim="paramsObj.content" resize="none" name="content" type="textarea" maxlength="500" style="width: 240px;height: 64px" />
          </el-form-item>
        </div>

      </el-form>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
// api
import { getIncomeType, getMarket } from '@/api/select';
import { getOrderKindList } from '@/api/config';

// components
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import Title from '@/components/Title';
import { getIpImageList } from '@/api/mengliOrder';
export default {
  components: { Title, selectWithoutHttp, selectWithUserLoad },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    isMakeUpOrder: { // 补差单
      type: Boolean,
      default: false
    },
    editLimt: {
      type: Boolean,
      default: false
    },
    isDisabledWithoutFile: {
      type: Boolean,
      default: false
    },
    isFileDisabled: {
      type: Boolean,
      default: false
    },
    disabledTaxAmount: {
      type: Boolean,
      default: false
    },
    taxAmountDisabled: {
      type: Boolean,
      default: false
    },
    disabledPlatformAccount: { // 是否已封账
      type: Boolean,
      default: false
    },
    tip: {
      type: String,
      default: ''
    },
    isHasBackground: {
      type: Boolean,
      default: true
    },
    noDisplayProps: {
      type: Array,
      default: () => ['projectType']
    }
  },
  data() {
    const validateSelect = (msg) => {
      return (rule, value, callback) => {
        const marketId = this.clientParams.marketId;
        if (!marketId || marketId === '') {
          callback(new Error(msg));
        } else {
          callback();
        }
      };
    };
    return {
      clientParams: {
        marketId: '',
        market: '',
        mastermindId: ''
      },
      paramsObj: {
        orderTime: new Date(new Date().toLocaleDateString()).getTime(),
        orderType: 0,
        taxAmount: null,
        incomeType: null,
        theme: '',
        remark: '',
        content: '',
        projectType: '',
        articlesPrice: '', // 刊例价
        discountPrice: '', // 折扣（自动计算）
        terminalType: '', // 终端品牌【新增】
        channelPrice: '', // 渠道价
        planPrice: '', // 策划价
        priceBase: '', // 结算基数
        orderSource: 1, // 订单来源
        orderKind: [], // 订单分类
        ip: []
      },
      rules: {
        orderTime: [{ required: true, trigger: 'change', message: '请选择下单日期' }],
        orderType: [{ required: true, trigger: 'change', message: '请选择订单类型' }],
        projectType: [{ required: true, trigger: 'change', message: '请选择项目类型' }],
        taxAmount: [{ required: true, trigger: 'blur', message: '请填写含税金额' }],
        articlesPrice: [{ required: true, trigger: 'blur', message: '请填写刊例价' }],
        incomeType: [{ required: true, trigger: 'change', message: '请选择收入类型' }],
        theme: [{ required: true, trigger: 'blur', message: '请填写品牌名称' }],
        content: [{ required: true, trigger: 'blur', message: '请填写文案内容' }],

        marketId: [{ required: true, trigger: 'change', validator: validateSelect('请填写销售名称') }]
      },
      projectTypesOptions: [], // 项目类型选项
      incomeOption: [], // 收入类型列表
      defaultMarketOption: [],
      defaultMastermindOption: [],
      marketOption: [], // 销售列表
      marketmindOption: [], // 策划执行人列表
      orderSourceOptions: [
        { id: 1, name: '飞博招商' },
        { id: 2, name: '达人个人引进' }
      ],
      defaultObjectUser: [],
      ipAry: []
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    orderTypeList() {
      const list = [{ value: 0, label: '原订单' }, { value: 4, label: '补录单' }];
      if (this.isEdit) {
        list.push({ value: 5, label: '调整单', disabled: true });
      }
      if (this.isEdit || this.isMakeUpOrder) {
        list.push({ value: 7, label: '补差单', disabled: true });
      }
      return list;
    }

  },
  created() {
    // 回填当前登录的用户
    const orderId = Number(this.$route.params.orderId) || null;
    if (this.userInfo && !orderId) {
      this.defaultMarketOption = [{ id: this.userInfo.id, value: this.userInfo.userName }];
      this.clientParams.marketId = this.userInfo.id;
      this.clientParams.market = this.userInfo.userName;
    }
    this.masketList('', 2);
    this.incomeTypeList();
    if (this.$refs.formRef) this.$refs.formRef.clearValidate();
  },
  methods: {
    getOrderKindList,
    isShowInput(prop) {
      return !(this.noDisplayProps.indexOf(prop) >= 0);
    },
    // 编辑时注入数据
    insertDetail(item) {
      const orderInfo = _.cloneDeep(item.orderInfo);
      const clientInfo = _.cloneDeep(item.clientInfo);
      this.ipAry = item.ipAry && item.ipAry.length ? _.cloneDeep(item.ipAry) : [];
      // 时间转换
      if (orderInfo.orderTime) orderInfo.orderTime = orderInfo.orderTime * 1000;
      // 已封账的话，订单类型置为调整单
      if (this.disabledPlatformAccount) orderInfo.orderType = 5;
      // 价格格式化（分 -> 元）
      if (orderInfo.taxAmount) { orderInfo.taxAmount = Number(orderInfo.taxAmount) / 100; }
      if (orderInfo.articlesPrice) { orderInfo.articlesPrice = Number(orderInfo.articlesPrice) / 100; }
      if (orderInfo.channelPrice) { orderInfo.channelPrice = Number(orderInfo.channelPrice) / 100; }
      if (orderInfo.planPrice) { orderInfo.planPrice = Number(orderInfo.planPrice) / 100; }

      if (orderInfo.priceBase) { orderInfo.priceBase = Number(orderInfo.priceBase) / 100; }
      this.orderTypeChange(orderInfo.orderType);
      if (clientInfo) {
        this.defaultMastermindOption = [{ id: clientInfo.mastermindId, value: clientInfo.mastermind }];
        this.defaultMarketOption = [{ id: clientInfo.marketId, value: clientInfo.market }];
        this.clientParams.marketId = clientInfo.marketId;
        this.clientParams.mastermindId = clientInfo.mastermindId;
      }
      for (const key in this.paramsObj) {
        this.paramsObj[key] = orderInfo[key];
      }
      this.paramsObj.ip = this.ipAry.map(item => {
        item = {
          name: `${item.ipFigure}/${item.ipSeries}`,
          ipName: item.ipFigure,
          ipId: item.ipFigureId,
          ipSeriesName: item.ipSeries,
          ipSeriesId: item.ipSeriesId
        };
        return item;
      });
    },
    /**
     * 获取下拉框的数据
     */
    // 获取收入类型的列表
    async incomeTypeList() {
      try {
        const result = await getIncomeType();
        this.incomeOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    // 获取ip形象
    getipFigure() {
      const a = function(params) {
        return new Promise((resolve, reject) => {
          params.name = '';
          if (params.userName) params.name = params.userName;
          delete params.userName;
          getIpImageList(params).then(res => {
            const { items } = res.data;
            items.forEach((item) => {
              item.name = `${item.ipName}/${item.ipSeriesName || '--'}`;
            });
            resolve(res);
          }).catch(err => {
            reject(err);
          });
        });
      };
      return a;
    },
    // 获取销售人/策划执行人的列表
    masketList(query = null, isMasket = 0) { // isMasket： 0为销售人， 1为策划执行人 2: 初始化
      getMarket(query).then(res => {
        if (isMasket === 0) {
          this.marketOption = res.data;
        } else if (isMasket === 1) {
          this.marketmindOption = res.data;
        } else {
          this.marketOption = res.data;
          this.marketmindOption = res.data;
        }
      });
    },
    /**
     * 参数改变时调用的方法  change methods
     */
    orderTypeChange(val) {
      this.$emit('orderTypeChange', val);
    },
    marketChange(item) {
      if (item) {
        this.clientParams.market = item.value;
      }
    },
    // 折扣价格计算
    mathDiscount() {
      const articlesPrice = this.paramsObj.articlesPrice;
      // 渠道价和策划价暂时隐藏
      // v2.1.6.1 折扣价格计算修改，（含税价/刊例价）改成（渠道价/刊例价）
      const channelPrice = this.paramsObj.channelPrice; // 渠道价
      if (articlesPrice && channelPrice) {
        let discountPrice = 0;
        if (Number(channelPrice) > 0 && Number(articlesPrice) > 0) {
          discountPrice = (Number(channelPrice) / Number(articlesPrice)).toFixed(2);
        }
        this.$set(this.paramsObj, 'discountPrice', discountPrice);
      }
    },
    // 策划价计算
    mathPlanPrice() {
      const taxAmount = this.paramsObj.taxAmount; // 含税金额
      const planPrice = this.paramsObj.planPrice; // 策划价
      // 渠道价 = 含税价 - 策划价
      if (taxAmount) {
        const price = (Number(taxAmount) - Number(planPrice)).toFixed(2);
        this.$set(this.paramsObj, 'channelPrice', price);
      }
      this.mathDiscount();
    },
    // ipAry的传值格式
    ipFigureChange(item) {
      this.ipAry = []; // 初始化数据
      item.map(val => {
        const obj = {
          ipFigure: val.ipName,
          ipFigureId: val.ipId,
          ipSeries: val.ipSeriesName,
          ipSeriesId: val.ipSeriesId
        };
        this.ipAry.push(obj);
      });
    },
    /** 其他方法 */
    // 提供给父组件来验证完整性
    validateForm(validate = true, index = 0) {
      return new Promise((resolve, reject) => {
        if (validate) {
          this.$refs.formRef.validate(valid => {
            if (valid) {
              resolve(valid);
            } else {
              reject(index);
            }
          });
        } else {
          resolve(true);
        }
      });
    },
    // 提供给父组件来获取参数
    getParams() {
      const params = _.cloneDeep(this.paramsObj);
      const clientParams = _.cloneDeep(this.clientParams);
      // 价格格式化（元 -> 分）
      if (params.taxAmount) {
        params.taxAmount = (Number(params.taxAmount) * 100).toFixed(0);
      }
      if (params.planPrice) {
        params.planPrice = (Number(params.planPrice) * 100).toFixed(0);
      }
      if (params.channelPrice) {
        params.channelPrice = (Number(params.channelPrice) * 100).toFixed(0);
      }
      if (params.articlesPrice) {
        params.articlesPrice = (Number(params.articlesPrice) * 100).toFixed(0);
      }
      if (params.discountPrice) {
        params.discountPrice = Number(params.discountPrice);
      }
      if (params.priceBase) {
        params.priceBase = (Number(params.priceBase) * 100).toFixed(0);
      }
      if (params.orderTime) {
        params.orderTime = parseInt(params.orderTime / 1000);
      }
      delete params.ip;
      return {
        orderInfo: params,
        clientInfo: clientParams,
        ipAry: this.ipAry
      };
    },
    numberInputChange(key) {
      if (this.paramsObj[key]) this.paramsObj[key] = Number(this.paramsObj[key]).toFixed(2);
    }
  }
};
</script>

<style lang="scss" scoped>
.order-info {
  background: #fff;
  border-radius: 12px;
  box-shadow:2px 4px 13px 0px rgba(221,225,234,1);
  padding: 24px;
}
.edit-order {
  display: flex;
  flex-wrap: wrap;
  .left {
    margin-right: 108px;
  }
  & ::v-deep {
    .el-form-item {
      .el-textarea__inner {
        height: 64px !important;
      }
      .el-form-item__label {
        width: 90px !important;
        line-height: 1.1 !important;
        display: flex;
        align-items: center;
        height: 32px;
      }
    }
  }
}
</style>
